package com.fz.study.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fz.study.project.entity.Course;
import com.fz.study.project.entity.StudentUser;
import com.fz.study.project.entity.dto.StudentCourseDto;
import com.fz.study.project.entity.qurey.StudentUserQuery;
import com.fz.study.project.enums.GenderEnum;
import com.fz.study.project.exception.BizException;
import com.fz.study.project.mapper.StudentUserMapper;
import com.fz.study.project.service.IStudentUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2024-02-07
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class StudentUserServiceImpl extends ServiceImpl<StudentUserMapper, StudentUser> implements IStudentUserService {
    private final StudentCourseServiceImpl studentCourseService;
    private final CourseServiceImpl courseService;
    @Override
    public void saveByName(StudentUser studentUser) {
        if (Objects.isNull(studentUser)){
            BizException.throwBizException("不能传递空的数据！");
        }
        StudentUser user = lambdaQuery().eq(StudentUser::getName, studentUser.getName()).one();
        if (!Objects.isNull(user)){
            BizException.throwBizException("用户已经存在！不需要重复添加！");
        }
        if (studentUser.getAge()<18){
            BizException.throwBizException("该系统需要学生年级超过18岁！");
        }
        save(studentUser);
    }

    @Override
    public Object listByName() {
        List<StudentUser> users =list();
        addItem(users);
        users.forEach(o->{
            GenderEnum.getEnumGender(o.getGender()).ifPresent(e -> o.setGenderText(e.getText()));
        });
        return users;
    }
//   联表查询到的数据直接显示到学生列表中
    private void addItem(List<StudentUser> records){
        if (!CollectionUtils.isEmpty(records)){
            //        根据传递的数据找到学生id
            Set<Integer> ids = records.stream().map(StudentUser::getId).collect(Collectors.toSet());
//        根据学生id在数据库中找到相应的课程信息
            List<StudentCourseDto> courseList = studentCourseService.lambdaQuery().in(StudentCourseDto::getStudentId,ids).list();
            log.info("课程信息为{}",courseList);
//        根据课程id对查询到的数据进行分类
            Map<Integer, List<StudentCourseDto>> collect = courseList.stream().collect(Collectors.groupingBy(StudentCourseDto::getStudentId));
            records.forEach(i -> {
//            先查询到课程id，再根据课程id在map集合中找到相应的map集合，之后再写入到course
                if (!Objects.isNull(collect.get(i.getId()))){
                    Set<Integer> courseId = collect.get(i.getId()).stream().map(StudentCourseDto::getCourseId).collect(Collectors.toSet());
                    List<Course> courses = courseService.lambdaQuery().in(Course::getId, courseId).list();
                    i.setCourses(courses);
                }
            });
        }
    }
    @Transactional
    @Override
    public void updateByName(StudentUser studentUser) {
        if (!StringUtils.hasLength(studentUser.getName()) || Objects.isNull(studentUser.getId())){
            BizException.throwBizException("修改信息中id和名字不能为空！");
        }
//        studentUser.setUpdateTime(LocalDateTime.now());
        saveOrUpdate(studentUser);
    }

    @Override
    @Transactional
    public void deleteByIds(List<Integer> ids) {
        removeByIds(ids);
    }
    @Override
    public Page<StudentUser> findByPage(StudentUserQuery studentUserQuery) {
        Page<StudentUser> query = new Page<>(studentUserQuery.getCurrent(), studentUserQuery.getSize());
        log.info("获取到的前端传递的数据为：{}",studentUserQuery);
        LambdaQueryWrapper<StudentUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(studentUserQuery.getId() != null
                        ,StudentUser::getId,studentUserQuery.getId())
                .like(StudentUser::getName,studentUserQuery.getName())
                .like(StudentUser::getPhone,studentUserQuery.getPhone());
        Page<StudentUser> doPage = page(query,wrapper);
//        doPage.getRecords()单独获取学生信息
        addItem(doPage.getRecords());
        return doPage;
    }
}
